package ca.clarity.hms.provider;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


/**
 * 환자 등록에 필요한 사진과 음성파일을 저장하기 위한 핸들러 클래스 이다.
 * 
 * @author Junghun, Shin
 * @version 1.0
 *
 */
public class HmsDatabaseHandler {

	public static final String TAG = HmsDatabaseHandler.class.getSimpleName();
	
	Context ctx;
	SQLiteDatabase db;
	HmsDatabaseHelper hmsDatabaseHelper;
	
	public HmsDatabaseHandler(Context ctx) {
		this.ctx = ctx;
		
		hmsDatabaseHelper = new HmsDatabaseHelper(ctx);
		
		db = hmsDatabaseHelper.getWritableDatabase();
	}
	
	/**
	 * database open.
	 * 
	 * @param ctx
	 * @return
	 */
	public static HmsDatabaseHandler open(Context ctx) {
		return new HmsDatabaseHandler(ctx);
	}
	
	/**
	 * Transaction 을 정의 한다.
	 */
	public void beginTransaction() {
		db.beginTransaction();
	}
	
	public void setTransactionSuccessful() {
		db.setTransactionSuccessful();
	}
	
	public void endTransaction() {
		db.endTransaction();
	}
	
	public SQLiteDatabase getSQLiteDatabase() {
		return this.db;
	}
	
	/**
	 * database close.
	 */
	public void close() {
		if(db.isOpen()) {
			db.close();
		}
	}
	
	/**
	 * HMS_PATIENT 테이블 컬럼 목록.
	 */
	private static final String[] HMS_PATIENT = new String[] {
		"_id", 
		"photo", 
		"interview"
	};
	
	/**
	 * patient 를 저장 한다.
	 * 
	 * @param values
	 * @return
	 */
	public Long insertHmsPatient(ContentValues values) {
		return db.insert("HMS_PATIENT", "", values);
	}
	
	/**
	 * patient 를 삭제 한다.
	 * 
	 * @return
	 */
	public int deleteHmsPatient() {
		return db.delete("HMS_PATIENT", null, null);
	}
	
	/**
	 * patient 목록을 가져 온다.
	 * 
	 * @return
	 */
	public ArrayList<HmsPatient> selectPatientList() {
		ArrayList<HmsPatient> hmsPatientList = new ArrayList<HmsPatient>();
		
//		Cursor cursor = db.query("hms_database", HMS_PATIENT, null, null, null, null, "_id ASC", null);
		Cursor cursor = db.rawQuery("select * from HMS_PATIENT order by _id ASC", null);
		
		try {
			HmsPatient hmsPatient;
			
			while(cursor.moveToNext()) {
				hmsPatient = new HmsPatient();
				
				hmsPatient.set_id(cursor.getString(0));
				hmsPatient.setPhoto(cursor.getBlob(1));
				hmsPatient.setInterview(cursor.getBlob(2));
				
				hmsPatientList.add(hmsPatient);
			}
		} catch(Exception e) {
			
		} finally {
			cursor.close();
		}
		
		return hmsPatientList;
	}
	
	/**
	 * patient 내용을 가져 온다.
	 * 
	 * @param _id
	 * @return
	 */
	public HmsPatient selectPatient(String _id) {
		HmsPatient hmsPatient = new HmsPatient();
		
		Cursor cursor = db.query("hms_database", HMS_PATIENT, "_id = ?", new String[] {_id}, null, null, null);
		
		cursor.moveToFirst();
		
//		hmsPatient.set_id(cursor.getString(0));
		
		cursor.close();
		
		return hmsPatient;
	}
}
